package com.ronglian.ucdisk.web;

import java.beans.PropertyEditorSupport;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

public class BaseController {
	
	@InitBinder  
	public void InitBinder(WebDataBinder dataBinder)  
	{  
	    dataBinder.registerCustomEditor(Date.class, new PropertyEditorSupport() {  
	    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	    	SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			@Override
			public String getAsText() {
				if (this.getValue() == null) {
					return "";
				}
				return this.sdf.format((Date) this.getValue());
			}

			@Override
			public void setAsText(String text) throws IllegalArgumentException {
				if (null == text || text.equals("")) {
					return;
				}
				try {
					if(text.length() > 15 ){
						this.setValue(this.sdfTime.parse(text));
					}else{
						this.setValue(this.sdf.parse(text));
					}
				} catch (Exception e) {
					this.setValue(new Date());
				}
			}
	    });
	    dataBinder.registerCustomEditor(Timestamp.class, new PropertyEditorSupport() {  
	    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

			@Override
			public String getAsText() {
				if (this.getValue() == null) {
					return "";
				}
				return this.sdf.format((Date) this.getValue());
			}

			@Override
			public void setAsText(String text) throws IllegalArgumentException {
				if (null == text || text.equals("")) {
					return;
				}
				try {
					this.setValue(this.sdf.parse(text));
				} catch (Exception e) {
					this.setValue(new Date());
				}
			}
	    });
	    
	    dataBinder.registerCustomEditor(int.class, new PropertyEditorSupport() {  


			@Override
			public void setAsText(String text) throws IllegalArgumentException {
				if (null == text || text.equals("")) {
					this.setValue(0);
				}else{
					this.setValue(Integer.valueOf(text));
				}
			}
	    });
	}
}
